package com.tnovoselec.android.travelassistant.async;

import java.util.List;
import java.util.Locale;
import java.util.concurrent.Callable;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;

import com.google.android.maps.GeoPoint;
import com.tnovoselec.android.common.io.LRUCache;

/**
 * Title: DKB ATM <br />
 * Copyright: Copyright (c) 2011 <br />
 * NTH Company: NTH d.o.o. <br />
 * 
 * @author Tomica Bosnjak
 * @version 1.1.0
 * @since 1.0.0
 */
public class TravelAssistantGeocoder implements Callable<GeoPoint> {

	private static final LRUCache<String, GeoPoint> GEOCODER_CACHE = new LRUCache<String, GeoPoint>(20);

	private final Context context;
	private final String addressText;
	private final String cacheKey;

	public TravelAssistantGeocoder(Context context, String addressText) {
		super();
		this.context = context;
		this.addressText = addressText;
		cacheKey = addressText.toLowerCase(); // Should be case sensitive!?
	}

	@Override
	public GeoPoint call() throws Exception {
		GeoPoint gp = TravelAssistantGeocoder.GEOCODER_CACHE.get(cacheKey);
		if (gp != null) {
			return gp;
		}

		Geocoder gc = new Geocoder(context, Locale.getDefault());
		List<Address> addressList = gc.getFromLocationName(addressText, 1);
		if ((addressList != null) && !addressList.isEmpty()) {
			Address address = addressList.get(0);

			gp = new GeoPoint((int) (address.getLatitude() * 1E6), (int) (address.getLongitude() * 1E6));
			TravelAssistantGeocoder.GEOCODER_CACHE.put(cacheKey, gp);
		}

		return gp;
	}
}
